package cn.imvc.app.models;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import cn.imvc.app.entities.AttrClass;
import cn.imvc.app.entities.PriceClass;
import cn.imvc.app.repositories.AttrClassRepository;
import cn.imvc.core.DialogBean;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;
@Service
public class AttrClassModelImpl implements AttrClassModel{

	@Autowired
	AttrClassRepository attrClassRepository;
	@Autowired
	AttrValueModel attrValueModel;
	@Autowired
	RefRelationModel refRelationModel;
	
	public Page<AttrClass> find(ViewRequest viewRequest) {
		
		return attrClassRepository.findAll(viewRequest);
	}

	public AttrClass get(int id) {
		
		return attrClassRepository.getOne(id);
	}
    
	public int save(AttrClass attrClass) {
		String code = attrClass.getCode();
		String name = attrClass.getName();
		List<AttrClass> pc = attrClassRepository.findByCode(code);
		List<AttrClass> pn= attrClassRepository.findByName(name);
		if(pc.size()>0){
		   return 0;
		}else if(pn.size()>0){
			return -1;
		}
		attrClassRepository.saveAndFlush(attrClass);
		return 	1;
	}

	public int update(int id,AttrClass attrClass) {
		AttrClass loadAttrClass = attrClassRepository.getOne(id);
		String code = attrClass.getCode();
		String name = attrClass.getName();
		List<AttrClass> pc = attrClassRepository.findByCode(code);
		List<AttrClass> pn= attrClassRepository.findByName(name);
		if(pc.size()>0&&!code.equals(loadAttrClass.getCode())){
		   return 0;
		}else if(pn.size()>0&&!name.equals(loadAttrClass.getName())){
			return -1;
		}
		BeanUtils.copyProperties(attrClass, loadAttrClass, new String[]{"id"});
		attrClassRepository.saveAndFlush(loadAttrClass);
		return 1;
	}

	public String delete(int id) {
		 String result = refRelationModel.deleteDateCheck("Attr_Class", "id", id);
		    if(result.equals("")){
		    	attrClassRepository.delete(id);
		    	return "";
		    }else{
		    	return result;
		    }
	}

	public void deleteBatch(int[] ids) {
		for(int id:ids){
			attrClassRepository.delete(id);
		}
		
	}

	
	

}
